<?php
/**
 * Created by PhpStorm.
 * User: lingyun
 * Date: 2018/5/7
 * Time: 21:14
 * Desc: 支付宝当面付
 */
namespace app\cash\controller;
use think\Controller;
use think\Db;
use think\Loader;
header('Content-type:text/html; Charset=utf-8');
Loader::import('alipay.pay.f2fpay.service.AlipayTradeService');
Loader::import('alipay.pay.aop.AopClient');
loader::import('alipay.pay.f2fpay.model.builder.AlipayTradePayContentBuilder');
class Alipay extends Controller{
    /**
     * @Author  lingyun
     * @Desc    支付宝支付
     */
    public function index(){
        return $this->fetch();
    }

    /**
     * @Author  lingyun
     * @Desc    支付宝支付
     * 2018-05-06
     */
    public function pay(){
        $order_id = input('param.order_id');
        $auth_code = input('param.auth_code');
        if(empty($auth_code)){
            $this->error('订单创建失败，请重新创建');
//            return ['code'=>0,'订单创建失败，请重新创建'];
        }

        if(empty($order_id)){
            $this->error('订单创建失败，请重新创建');
//            return ['code'=>0,'msg'=>'订单创建失败，请重新创建'];
        }
        $order = db('order')->where('id',$order_id)->find();
        if(empty($order)){
            $this->error('订单创建失败，请重新创建');
//            return ['code'=>0,'msg'=>'订单创建失败，请重新创建'];
        }
        if($order['pay_status'] == 1){          //已经支付
            $this->success(2,'');
//            return ['code'=>1,'msg'=>'支付成功'];
        }

        $root = request()->domain();                        //网站更目录

        $config = config('alipay');                         //支付宝配置信息
        $config['notify_url'] = $root.'/index.php/index/dangmianfu/alipay_notify';
//        $config['return_url'] = $root.'/index.php/index/dangmianfu/alipay_notify';
        $appid = $config['app_id'];  //https://open.alipay.com 账户中心->密钥管理->开放平台密钥，填写添加了电脑网站支付的应用的APPID
//        $outTradeNo = $this->build_order_no($store_id);     //你自己的商品订单号
        $payAmount = $order['final_amount'];          //付款金额，单位:元

        $orderName = '支付测试';    //订单标题
        $signType = 'RSA2';       //签名算法类型，支持RSA2和RSA，推荐使用RSA2
        $body = '扫码支付';
        $subject = '支付宝支付';
//商户私钥，填写对应签名算法类型的私钥，如何生成密钥参考：https://docs.open.alipay.com/291/105971和https://docs.open.alipay.com/200/105310
        $saPrivateKey=$config['merchant_private_key'];


        $qrPayRequestBuilder = new \AlipayTradePayContentBuilder();
        $qrPayRequestBuilder->setOutTradeNo($order['order_sn']);
        $qrPayRequestBuilder->setTotalAmount($payAmount);
        $qrPayRequestBuilder->setAuthCode($auth_code);
        $qrPayRequestBuilder->setTimeExpress("5m");
        $qrPayRequestBuilder->setSubject($subject);
//        $qrPayRequestBuilder->setBody($body);

// 调用barPay方法获取当面付应答
        $qrPay = new \AlipayTradeService($config);
        $qrPayResult = $qrPay->barPay($qrPayRequestBuilder);

        $data = [];
        $data['status'] = $qrPayResult->getTradeStatus(); // SUCCESS/FAILED/UNKNOWN
        $response = json_decode(json_encode($qrPayResult->getResponse()), true);
//        file_put_contents('dangmianfu.txt',json_encode($qrPayResult->getResponse()));
        trace('alipay:' . json_encode($response), 'log');
        $data['message'] = $response['msg'];
        if ($data['status'] == 'SUCCESS') {
            $data['outer_sn'] = $response['out_trade_no'];
            $order = db('order')->where('order_sn',$data['outer_sn'])->find();
            $store = db('store')->where('id',$order['store_id'])->find();
            if($order['pay_status'] == 1){
                return ['code'=>1,'msg'=>'支付成功'];
            }else{      //更新订单状态
                db('order')->where('order_sn',$data['outer_sn'])->update(['pay_status'=>1,'pay_time'=>time(),'pay_code'=>$data['outer_sn'],'order_status'=>4]);
                db('order_details')->where('order_id',$order['id'])->update(['status'=>4]);
                $order_action_arr = [
                    'uid'=>$order['uid'],
                    'order_id'=>$order['id'],
                    'action_user'=>0,
                    'order_status'=>4,
                    'pay_status'=>1,
                    'status_desc'=>'订单已完成',
                    'storeid'=>$order['store_id'],
                    'addtime'=>time()
                ];
                db('order_action')->insert($order_action_arr);          //插入订单动作信息

                $pay_log_arr = [
                    'order_id'=>$order['id'],
                    'order_sn'=>$order['order_sn'],
                    'order_type'=>2,
                    'uid'=>$order['uid'],
                    'pay_type'=>$order['pay_type'],
                    'pay_sign'=>1,
                    'store_id'=>$order['store_id'],
                    'amount'=>$order['final_amount'],
                    'remark'=>'线下购买商品，订单号'.$order['order_sn'].'，总价：'.$order['final_amount'],
                    'addtime'=>time()
                ];
                db('pay_log')->insert($pay_log_arr);            //新增支付记录

                third_tier_distribution($order['uid'],$order['final_amount'],$order['store_id'],$order['id'],0,$order['order_sn'],$order['pay_type']);           //三级分销返积分

                $casher = db('system_user')->where('id',$order['cashier'])->find();

                //小票内容
                $content = '';

                $content .= '<tr><td colspan="4" style="font-size: large;text-align: center">'.$store["title"].'</td></tr><tr><td colspan="4" style="font-size: large;text-align: center">&nbsp;</td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller">单号 ' . $order["order_sn"] . '</td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller">收银员 ' . $casher["realname"] . '</td></tr><tr><td colspan="4" style="text-align: center">———————————————</td></tr><tr><td style="width: 25mm;">商品</td><td>数量</td><td>单价</td><td>小计</td></tr>';

                $order_details = db('order_details')->alias('a')->join('ys_goods b','a.goods_id=b.id','LEFT')->where('a.order_id',$order['id'])->field('a.id,a.goods_id,a.store_goods_stock_id,a.spec_detail,b.name,a.goods_num,a.final_amount,spec_price')->select();

                foreach($order_details as $k => $v){
                    $content .= '<tr style="font-size: smaller;"><td colspan="4" style="text-align: left">' . $v['name'].' '.$v["spec_detail"] . '</td></tr>';
                    $content .= '<tr style="font-size: smaller;"><td style="width: 25mm"></td><td>' . $v["goods_num"] . '</td><td>' . floatval($v['spec_price']) . '</td><td>' . $v['final_amount'] . '</td></tr>';


                    $stock = db('store_goods_stock')->where('id',$v['store_goods_stock_id'])->find();
                    $cur_stock = $stock['stock'] - $v['goods_num'];
                    //更新门店库存
                    db('store_goods_stock')->where('id',$v['store_goods_stock_id'])->update(['stock'=>$cur_stock]);
                    $arr = [
                        'goods_id'=>$v['goods_id'],
                        'goods_spec_id'=>$stock['goods_spec_id'],
                        'title'=>$v['spec_detail'],
                        'order_id'=>$order['id'],
                        'store_id'=>$order['store_id'],
                        'ruku_num'=>0,
                        'tuihuo_num'=>0,
                        'chuku_num'=>$v['goods_num'],
                        'sunhao_num'=>0,
                        'remark'=>$order['order_sn'],
                        'cur_stock'=>$cur_stock,
                        'addtime'=>time(),
                        'order_sn'=>$order['order_sn']
                    ];
                    db('store_goods_log')->insert($arr);
                }

                $content .= '<tr><td colspan="4" style="text-align: center">———————————————</td></tr>';

                switch ($order['pay_type']) {
                    case 1:
                        $method = '支付宝';
                        break;
                    case 2:
                        $method = '微信';
                        break;
                    case 3:
                        $method = '余额';
                        break;
                    case 4:
                        $method = '现金';
                        break;
                    case 5:
                        $method = '银行卡';
                        break;
                    default:
                        break;
                }

                $content .= '<tr><td colspan="4" style="text-align: left;font-size: smaller">总数量：' . $order["goods_num"] . ' 合计：￥' . $order["final_amount"] . '</td></tr><tr><td colspan="4" style=";text-align: center">&nbsp;</td></tr>';

                if(!empty($order['uid'])){
                    $member = db('user')->where('uid',$order['uid'])->find();
                    if(!empty($member)){
                        $content .='<tr><td colspan="4" style="text-align: left;font-size: smaller">姓名：' . $member["realname"] . '     手机：￥' . $member["mobile"] . '</td></tr><tr><td colspan="4" style=";text-align: center">&nbsp;</td></tr>';

                        $content .='<tr><td colspan="4" style="text-align: left;font-size: smaller">会员卡：' . $member["pay_code"] . '     余额：￥' . $member["user_money"] . '</td></tr><tr><td colspan="4" style=";text-align: center">&nbsp;</td></tr>';
                    }
                }

                //            $content .='<tr><td colspan="4" style="text-align: left;font-size: smaller">折扣：暂无</td></tr><tr><td colspan="4" style=";text-align: center">&nbsp;</td></tr>';

                $content .= '<tr><td colspan="4" style="text-align: left">' . '欢迎您再次光临' . '</td></tr>';
                $content .= '<tr><td colspan="4" style="text-align: left">' . date('Y-m-d H:i:s') . '</td></tr>';
                $this->success(2,'',$content);
            }

        } else {
            $data['message'] .= $response['sub_msg'];
            $this->error($data['message']);
        }


    }

    /**
     * @Author  lingyun
     * @Desc    生成订单
     * @return string
     */
    private function build_order_no($store_id){
        return date('YmdHis') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8).$store_id;
    }


}
